package com.handpay.framework.upcard;

import android.text.TextUtils;

import com.handpay.framework.upcard.sdom.DomLite;
import com.handpay.framework.upcard.sdom.TagNode;
import com.handpay.zztong.hp.log.HPLog;

import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Locale;

public class UPXMLRespParser
{
	public final static String						SEPARTOR		= "|";								// 分隔符
	private final Hashtable<String, String>			hash_elements	= new Hashtable<String, String>();
	private final static Hashtable<Integer, String>	upcardXmlIS		= new Hashtable<Integer, String>();
	private final static Hashtable<String, Integer>	upcardXmlSI		= new Hashtable<String, Integer>();
	private static UPXMLRespParser						upcardxml;
	public final static String RESPOK = "00";//
	public final static String RESPXU = "XU";
	public final static String XPAPP = "cupMobile:application";// 支付应用名称
	public final static String XPVERSION = "cupMobile:version";// 版本号
	public final static String XPRESPCODE = "cupMobile.transaction.responseCode";// 操作结果
	public final static String XPSERVICEINFO = "cupMobile.transaction.serviceInfo"; // 服务信息
	public final static String XPACCOUNTBALANCE = "cupMobile.transaction.accountBalance"; // 账户余额
	public final static String XPMAC = "cupMobile.mac";// MAC
	public static UPXMLRespParser getInstance()
	{
		if (upcardxml == null)
		{
			upcardxml = new UPXMLRespParser();
		}
		if (upcardXmlIS.isEmpty())
		{
			upcardXmlIS.put(1, XPAPP);// 支付应用名称
			upcardXmlIS.put(2, XPVERSION);     // 版本号
			upcardXmlIS.put(3, "cupMobile.transaction:type");// 交易类型
			upcardXmlIS.put(4, "cupMobile.transaction.submitTime");// 交易提交时间
			upcardXmlIS.put(5, "cupMobile.transaction.merchant:id");// 商户代码
			upcardXmlIS.put(6, "cupMobile.transaction.merchant:name");// 商户名称
			upcardXmlIS.put(7, "cupMobile.transaction.merchant:country");// 商户国家代码
			upcardXmlIS.put(8, "cupMobile.transaction.terminal:id");// 子商户终端代码
			upcardXmlIS.put(9, "cupMobile.transaction.order:id");// 订单号?
			upcardXmlIS.put(10, "cupMobile.transaction.settleDate");// 清算日期
			upcardXmlIS.put(11, "cupMobile.transaction.transAmount");// 交易金额
			upcardXmlIS.put(12, "cupMobile.transaction.transAmount:currency");// 交易币种
			upcardXmlIS.put(13, "cupMobile.transaction.billAmount");// 扣账金额
			upcardXmlIS.put(14, "cupMobile.transaction.billAmount:currency");// 扣账币种
			upcardXmlIS.put(15, "cupMobile.transaction.billAmount:convertRate");// 扣账汇率
			upcardXmlIS.put(16, "cupMobile.transaction.accountNumber1");// 账户1
			upcardXmlIS.put(17, "cupMobile.transaction.pin");// 个人身份标识?
			upcardXmlIS.put(19, XPRESPCODE);// 应答?
			upcardXmlIS.put(20, "cupMobile.transaction.origSubmitTime");// 原始交易提交时间
			upcardXmlIS.put(24, "cupMobile.transaction.transSerialNumber");// 交易流水?
			upcardXmlIS.put(25, "cupMobile.transaction.track2Data");// 磁道2数据
			upcardXmlIS.put(26, "cupMobile.transaction.track3Data");// 磁道3数据
			upcardXmlIS.put(27, "cupMobile.transaction.cardholderIdInfo");// 持卡人身份信?
			upcardXmlIS.put(28, "cupMobile.transaction.cardSerialNumber");// 终端芯片序列?
			upcardXmlIS.put(29, "cupMobile.transaction.cmspReserved");// CMSP保留使用
			upcardXmlIS.put(30, XPACCOUNTBALANCE);// 账户余额
			upcardXmlIS.put(31, "cupMobile.transaction.accountBalance:currency");// 账户余额币种
			upcardXmlIS.put(32, "cupMobile.transaction.upCashData");// 电子钱包数据
			upcardXmlIS.put(33, "cupMobile.transaction.accountNumber2");// 帐户2
			upcardXmlIS.put(34, "cupMobile.transaction.expireDate");// 卡有效期
			upcardXmlIS.put(35, XPSERVICEINFO);// 服务信息
			upcardXmlIS.put(36, "cupMobile.transaction.dynamicKeyData");// 动?密钥数据
			upcardXmlIS.put(37, "cupMobile.securityChipTp");// 安全载体类型
			upcardXmlIS.put(38, "cupMobile.transaction.SpId");// SP代码
			upcardXmlIS.put(39, "cupMobile.transaction.ICNumber");// 卡片序列?
			upcardXmlIS.put(40, "cupMobile.transaction.SysProvide");// 系统支持?
			upcardXmlIS.put(41, "cupMobile.transaction.OrgTransSerNo");// 原交易流水号
			upcardXmlIS.put(42, "cupMobile.transaction.creditAcctBal");// 信用卡账户余?
			upcardXmlIS.put(43, "cupMobile.transaction.creditAcctBal:currency");// 信用卡账户余额币?
			upcardXmlIS.put(251, "cupMobile.transaction.DCData");// 借贷记应用数?
			upcardXmlIS.put(252, "cupMobile.merchantAuthentication.digest");// 商户摘要数据
			upcardXmlIS.put(253, "cupMobile.merchantAuthentication.signature");// 商户数字签名
			upcardXmlIS.put(254, "cupMobile.senderSignature");// 发?方数字签?
			upcardXmlIS.put(255, XPMAC);// 报文鉴别?
		}
		if (upcardXmlSI.isEmpty())
		{
			for (Iterator<Integer> itr = upcardXmlIS.keySet().iterator(); itr
					.hasNext();)
			{
				Integer key = itr.next();
				String value = upcardXmlIS.get(key).toLowerCase(Locale.US);
				upcardXmlSI.put(value, key);
			}
		}
		return upcardxml;
	}
	
	/**
	 * 解析银联返回报文
	 * 
	 * @param respBuffer
	 * @return
	 */
	public Hashtable<String, String> parseResp(byte respBuffer[])
	{
		hash_elements.clear();
		DomLite dom = new DomLite();
		TagNode root = dom.load(respBuffer, "UTF-8");
		if (root == null)
		{
			return null;
		}
		build(root, "");
		return hash_elements;
	}
	
	/**
	 * 组织MAC的明文?
	 * 
	 * @param resp
	 * @return
	 */
	public String macPlain(Hashtable<String, String> resp)
	{
		StringBuffer sb = new StringBuffer();
		String[] sbtemp = new String[255];
		for (Iterator<String> itr = resp.keySet().iterator(); itr.hasNext();)
		{
			String key = itr.next();
			String value = resp.get(key);
			HPLog.i("macPlain",key + " : " + value);
			Integer iKey = upcardXmlSI.get(key);
			HPLog.i("iKey","" + iKey);
			if (iKey == 4 || iKey == 5 || iKey == 8 || iKey == 9 || iKey == 10
					|| iKey == 11 || iKey == 12 || iKey == 13 || iKey == 14
					|| iKey == 15 || iKey == 16 || iKey == 19 || iKey == 20
					|| iKey == 24 || iKey == 25 || iKey == 26 || iKey == 28
					|| iKey == 33 || iKey == 34 || iKey == 39 || iKey == 251
					|| iKey == 252)
			{
//				if (sb.length() > 0)
//				{
//					sb.append(" ");
//				}
//				sb.append(value);
				sbtemp[iKey] = value;
			}
		}
		for(int i = 0;i < sbtemp.length;i ++)
		{
			if(TextUtils.isEmpty(sbtemp[i]))
			{
				continue;
			}
			if (sb.length() > 0)
			{
				sb.append(" ");
			}
			sb.append(sbtemp[i]);
		}
		if (sb.length() > 0)
		{
			return sb.toString();
		}
		return null;
	}
	
	private String build(TagNode node, String path)
	{
		if (node == null)
		{
			return "";
		}
		
		String newPath = buildTag(node, path);
		
		for (TagNode child = node.getChild(0); child != null; child = child
				.getSibling())
		{
			build(child, newPath);
		}
		
		return newPath;
	}
	
	private String buildTag(TagNode node, String curPath)
	{
		// String path = curPath;
		
		if (node.getTagType() == TagNode.TAG_TEXT)
		{
			// hash_elements.put(curPath.toLowerCase(), node.getName());
			// Caojun 多条记录用分隔符分割
			String key = curPath.toLowerCase(Locale.US);
			String v = node.getName();
			String oldv = hash_elements.get(key);
			if (oldv != null)
			{
				// 有多条?
				String newv = oldv + SEPARTOR + v;
				hash_elements.put(key, newv);
			}
			else
			{
				hash_elements.put(key, v);
			}
			return curPath;
		}
		
		if (curPath.length() <= 0)
		{
			curPath = node.getName();
		}
		else
		{
			curPath = curPath + "." + node.getName();
		}
		
		Hashtable<String, String> attrs = node.getAttributes();
		if (attrs != null)
		{// attributes
			for (Enumeration<?> keys = node.getAttributes().keys(); keys
					.hasMoreElements();)
			{
				String k = (String) keys.nextElement();
				String v = node.getAttributes().get(k);
				
				String key = (curPath + ":" + k).toLowerCase(Locale.US);
				// Caojun 多条记录用分隔符分割
				String oldv = hash_elements.get(key);
				if (oldv != null)
				{
					// 有多条记录?
					String newv = oldv + SEPARTOR + v;
					hash_elements.put(key, newv);
				}
				else
				{
					hash_elements.put(key, v);
				}
			}
		}
		
		return curPath;
	}
}
